﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TomNet.App.Core.Contracts;
using TomNet.App.Model.DB;
using TomNet.App.Core.Contracts.Identity;
using TomNet.App.Model.DTO;
using TomNet.AspNetCore.Data;
using TomNet.SqlSugarCore.Entity;
using TomNet.Security.Claims;
using System.Security.Claims;
using TomNet.App.Model.DB.Identity;

namespace TomNet.App.Web.Controllers
{
    [Authorize]
    [Description("人员管理")]
    public class UserController : Controller
    {
        private readonly IUsersContract _usersContract;
        private readonly IUserMapContract _userMapContract;
        private readonly IUserLoginContract _userLoginContract;
        private readonly IUserRoleMapContract _userRoleMapContract;
        private readonly IUnitOfWork _unitOfWork;
        public UserController(IUsersContract usersContract,
            IUserMapContract userMapContract,
            IUserLoginContract userLoginContract,
            IUserRoleMapContract userRoleMapContract,
            IUnitOfWork unitOfWork)
        {
            _usersContract = usersContract;
            _userMapContract = userMapContract;
            _userLoginContract = userLoginContract;
            _userRoleMapContract = userRoleMapContract;
            _unitOfWork = unitOfWork;
        }

        [Description("业务员列表")]
        [HttpGet]
        public IActionResult SalesmanList()
        {
            return View();
        }
        [Description("接口商列表")]
        [HttpGet]
        public IActionResult InterfaceList()
        {
            return View();
        }
        [Description("代理商列表")]
        [HttpGet]
        public IActionResult AgentList()
        {
            return View();
        }
        [Description("客户列表")]
        [HttpGet]
        public IActionResult GuestList()
        {
            return View();
        }
        [Description("人员列表")]
        [HttpPost]
        public IActionResult UserList(int intType = 0,int page = 1, int limit = 20)
        {
            //inttype  1 系统管理员 2，业务员（2，4，6）3，接口
            var query = _usersContract.UnitOfWork.DbContext.Queryable<UserLogin, UserRoleMap, Role,Users>((ul, urm, r,ui)
                => urm.UserId == ul.UserID && urm.RoleId == r.Id && ul.UserID == ui.Id)
                .Where((ul, urm, r, ui) => r.Id == intType)  
                .OrderBy((ul, urm, r, ui) => ul.Id, OrderByType.Desc)
               .Select((ul, urm, r, ui) => new UserDto
               {   
                   LoginId = ul.Id,
                   UserName = ui.UserName,
                   UserId = ui.Id,
                   RoleName = r.Name,
                   RoleId = r.Id,
                   Email = ui.Email,
                   Phone = ui.Phone,
                   IdNumber = ui.IdNumber,
                   Sex = ui.Sex,
                   CreatedTime = ui.CreatedTime
               });       
            int total = 0;
            var list = query.ToPageList(page, limit, ref total);
            var result = new LayuiPageResult<UserDto>
            {
                Code = 0,
                Msg = "Success",
                Count = total,
                Data = list.ToArray()
            };

             return Json(result);
        }
        [Description("业务人员列表")]
        [HttpPost]
        public IActionResult SalemanList(int intType = 0)
        {
            //inttype  1 系统管理员 2，业务员（2，4，6）3，接口
            var query = _usersContract.UnitOfWork.DbContext.Queryable<UserLogin, UserRoleMap, Role, Users>((ul, urm, r, ui)
                 => urm.UserId == ul.UserID && urm.RoleId == r.Id && ul.UserID == ui.Id)
                .Where((ul, urm, r, ui) => r.Id == intType)
                .OrderBy((ul, urm, r, ui) => ul.Id, OrderByType.Desc)
               .Select((ul, urm, r, ui) => new UserDto
               {
                   LoginId = ul.Id,
                   UserName = ui.UserName,
                   UserId = ui.Id,
                   RoleName = r.Name,
                   RoleId = r.Id,
                   Email = ui.Email,
                   Phone = ui.Phone,
                   IdNumber = ui.IdNumber,
                   Sex = ui.Sex,
                   CreatedTime = ui.CreatedTime
               }).ToArray();            
            AjaxResult result = new AjaxResult
            {
                Type = Data.AjaxResultType.Success,
                Content = "操作成功",
                Data = query
            };
            return Json(result);           
        }        
        [Description("业务员添加")]
        [HttpGet]
        public IActionResult SalesmanInsert()
        {
            return View();
        }
        [Description("业务员添加")]
        [HttpPost]
        public IActionResult SalesmanInsert(UserAll user)
        {            
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            user.ProportionID = 0;
            user.Token = "";
            user.CreatedTime = DateTime.Now;
            user.IsDeleted = false;
            try
            {
                _usersContract.UnitOfWork.BeginTran();
                var dd = _usersContract.InsertReturnEntity(user);
                UserLogin userLogin = new UserLogin();
                userLogin.UserID = dd.Id;
                userLogin.LoginName = user.Phone;
                userLogin.Password = "123456";
                userLogin.LoginType = 0;
                userLogin.IsDeleted = false;
                _userLoginContract.Insert(userLogin);

                UserRoleMap userRoleMap = new UserRoleMap();
                userRoleMap.UserId = user.Id;
                userRoleMap.RoleId = user.RoleID;
                _userRoleMapContract.Insert(userRoleMap);

                UserMap userMap = new UserMap();
                userMap.UserId = dd.Id;
                userMap.AgentId = user.AgentID;
                userMap.AgentSalesmanId = user.AgentSalesmanID;
                userMap.InterfaceId = user.InterfaceID;
                userMap.InterfaceSalesmanId = user.InterfaceSalesmanID;
                userMap.SuperId = 1;
                userMap.SuperSalesmanId = user.SuperSalesmanID;
                if (user.RoleID == 2)
                {
                    userMap.SuperSalesmanId = dd.Id;
                }
                else if (user.RoleID == 4)
                {
                    userMap.InterfaceSalesmanId = dd.Id;
                }
                else if (user.RoleID == 6)
                {
                    userMap.AgentSalesmanId = dd.Id;
                }
                _userMapContract.Insert(userMap);
                result.Content = "操作成功";
                result.Type = Data.AjaxResultType.Success;
                _usersContract.UnitOfWork.Commit();

            }
            catch (Exception ex)
            {
                result.Content = ex.Message;
                _usersContract.UnitOfWork.Rollback();
            }
            return Json(result);           
        }
        [Description("业务员修改")]
        [HttpGet]
        public IActionResult SalesmanEdit(int id)
        {
            //var goods = _usersContract.Entities.AsQueryable().Where(m => m.Id == id).First();
            //ViewBag.password = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Password;
            //return View(goods);
            var goods = _usersContract.Entities.AsQueryable().Where(m => m.Id == id).First();
            ViewBag.password = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Password;
            ViewBag.loginid = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Id;
            return View(goods);
        }
        [Description("业务员修改")]
        [HttpPost]
        public IActionResult SalesmanEdit(UserDto UserDto)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            try
            {
                //开启事务
                _usersContract.UnitOfWork.DbContext.BeginTran();
                var n = _userLoginContract.Update(new UserLogin { Id = UserDto.LoginId, UserID = UserDto.UserId, LoginName = UserDto.Phone, Password = UserDto.Phone, LoginType = 1, IsDeleted = false });
                var i = _usersContract.Update(new Users
                {
                    Id = UserDto.UserId,
                    UserName = UserDto.UserName,
                    ProportionID = UserDto.ProportionID,
                    Email = UserDto.Email,
                    Phone = UserDto.Phone,
                    IdNumber = UserDto.IdNumber,
                    Sex = UserDto.Sex,
                    RoleID = UserDto.RoleId,
                    CreatedTime = UserDto.CreatedTime,
                    Token = "",
                    IsDeleted = false,

                });
                _usersContract.UnitOfWork.DbContext.CommitTran();
                if (n == 1 && i == 1)
                {
                    result.Content = "操作成功";
                    result.Type = Data.AjaxResultType.Success;
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                _usersContract.UnitOfWork.DbContext.RollbackTran();
                result.Content = ex.Message;                
            }
            return Json(result);
        }
        [Description("人员删除")]
        [HttpPost]
        public IActionResult UserDelete(int id)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            try
            {
                //开启事务
                _usersContract.UnitOfWork.DbContext.BeginTran();
                var n = _usersContract.Delete(id);// new UserInfo{UserId= id } );

                var m = _userRoleMapContract.Delete(x => x.UserId == id);

                var z = _userLoginContract.Delete(x=>x.UserID ==id);
                var y = _userMapContract.Delete(x => x.UserId == id);

                //提交事务
                _usersContract.UnitOfWork.DbContext.CommitTran();
                if (n == 1 && m == 1 && z == 1 && y==1)
                {
                    result.Content = "操作成功";
                    result.Type = Data.AjaxResultType.Success;
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                _usersContract.UnitOfWork.DbContext.RollbackTran();
                throw ex;
            }
            return Json(result);
        }
        [Description("接口商添加")]
        [HttpGet]
        public IActionResult InterfaceInsert()
        {
            return View();
        }
        [Description("接口商添加")]
        [HttpPost]
        public IActionResult InterfaceInsert(Users user)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            user.ProportionID = 0;
            user.Token = "";
            user.CreatedTime = DateTime.Now;
            user.IsDeleted = false;
            try
            {
                _usersContract.UnitOfWork.BeginTran();
                var dd = _usersContract.InsertReturnEntity(user);
                UserLogin userLogin = new UserLogin();
                userLogin.UserID = dd.Id;
                userLogin.LoginName = user.Phone;
                userLogin.Password = "123456";
                userLogin.LoginType = 0;
                userLogin.IsDeleted = false;
                _userLoginContract.Insert(userLogin);

                UserRoleMap userRoleMap = new UserRoleMap();
                userRoleMap.UserId = user.Id;
                userRoleMap.RoleId = user.RoleID;
                _userRoleMapContract.Insert(userRoleMap);

                UserMap userMap = new UserMap();
                userMap.UserId = dd.Id;
                userMap.AgentId = 0;
                userMap.AgentSalesmanId = 0;
                userMap.InterfaceId = dd.Id;
                userMap.InterfaceSalesmanId = 0;
                userMap.SuperId = 1;
                userMap.SuperSalesmanId = 2;
                _userMapContract.Insert(userMap);
                result.Content = "操作成功";
                result.Type = Data.AjaxResultType.Success;
                _usersContract.UnitOfWork.Commit();

            }
            catch (Exception ex)
            {
                result.Content = ex.Message;
                _usersContract.UnitOfWork.Rollback();
            }
            return Json(result);
        }
        [Description("接口商修改")]
        [HttpGet]
        public IActionResult InterfaceEdit(int id)
        {
            
            var goods = _usersContract.Entities.AsQueryable().Where(m => m.Id == id).First();
            ViewBag.password = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Password;
            ViewBag.loginid = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Id; 
            return View(goods);
        }
        [Description("接口商修改")]
        [HttpPost]
        public IActionResult InterfaceEdit(UserDto UserDto)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            try
            {
                //开启事务
                _usersContract.UnitOfWork.DbContext.BeginTran();
                var n = _userLoginContract.Update(new UserLogin { Id=UserDto.LoginId, UserID = UserDto.UserId, LoginName = UserDto.Phone, Password = UserDto.Phone, LoginType = 1, IsDeleted = false });
                var i = _usersContract.Update(new Users
                {
                    Id = UserDto.UserId,
                    UserName = UserDto.UserName,
                    ProportionID = UserDto.ProportionID,
                    Email = UserDto.Email,
                    Phone = UserDto.Phone,
                    IdNumber = UserDto.IdNumber,
                    Sex = UserDto.Sex,
                    RoleID = UserDto.RoleId,
                    CreatedTime = UserDto.CreatedTime,
                    Token = "",
                    IsDeleted = false,                    

                });
                _usersContract.UnitOfWork.DbContext.CommitTran();
                if (n == 1 && i == 1)
                {
                    result.Content = "操作成功";
                    result.Type = Data.AjaxResultType.Success;
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                _usersContract.UnitOfWork.DbContext.RollbackTran();
                result.Content = ex.Message;
            }
            return Json(result);
        }
        [Description("代理商添加")]
        [HttpGet]
        public IActionResult AgentInsert()
        {
            return View();
        }
        [Description("代理商添加")]
        [HttpPost]
        public IActionResult AgentInsert(UserAll user)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            user.ProportionID = 0;
            user.Token = "";
            user.CreatedTime = DateTime.Now;
            user.IsDeleted = false;
            try
            {
                _usersContract.UnitOfWork.BeginTran();
                var dd = _usersContract.InsertReturnEntity(user);
                UserLogin userLogin = new UserLogin();
                userLogin.UserID = dd.Id;
                userLogin.LoginName = user.Phone;
                userLogin.Password = "123456";
                userLogin.LoginType = 0;
                userLogin.IsDeleted = false;
                _userLoginContract.Insert(userLogin);

                UserRoleMap userRoleMap = new UserRoleMap();
                userRoleMap.UserId = user.Id;
                userRoleMap.RoleId = user.RoleID;
                _userRoleMapContract.Insert(userRoleMap);
                 
                UserMap userMap = new UserMap();
                userMap.UserId = dd.Id;
                userMap.AgentId = dd.Id;
                userMap.AgentSalesmanId = 0;

                userMap.InterfaceId = user.InterfaceID;
                userMap.InterfaceSalesmanId = 0;
                userMap.SuperId = 1;
                userMap.SuperSalesmanId = 2;
                _userMapContract.Insert(userMap);
                result.Content = "操作成功";
                result.Type = Data.AjaxResultType.Success;
                _usersContract.UnitOfWork.Commit();

            }
            catch (Exception ex)
            {
                result.Content = ex.Message;
                _usersContract.UnitOfWork.Rollback();
            }
            return Json(result);
        }
        [Description("代理商修改")]
        [HttpGet]
        public IActionResult AgentEdit(int id)
        {
            var goods = _usersContract.Entities.AsQueryable().Where(m => m.Id == id).First();
            ViewBag.password = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Password;
            ViewBag.loginid = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Id;
            ViewBag.interfaceId = _userMapContract.Entities.AsQueryable().Where(m => m.UserId == goods.Id).First().InterfaceId;
            return View(goods);
        }
        [Description("代理商修改")]
        [HttpPost]
        public IActionResult AgentEdit(UserDto UserDto)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            try
            {
                //开启事务
                _usersContract.UnitOfWork.DbContext.BeginTran();
                var n = _userLoginContract.Update(new UserLogin { Id = UserDto.LoginId, UserID = UserDto.UserId, LoginName = UserDto.Phone, Password = UserDto.Phone, LoginType = 1, IsDeleted = false });
                var i = _usersContract.Update(new Users
                {                    
                    Id = UserDto.UserId,
                    UserName = UserDto.UserName,
                    ProportionID = UserDto.ProportionID,
                    Email = UserDto.Email,
                    Phone = UserDto.Phone,
                    IdNumber = UserDto.IdNumber,
                    Sex = UserDto.Sex,
                    RoleID = UserDto.RoleId,
                    CreatedTime = UserDto.CreatedTime,
                    Token = "",
                    IsDeleted = false,

                });
                _usersContract.UnitOfWork.DbContext.CommitTran();
                if (n == 1 && i == 1)
                {
                    result.Content = "操作成功";
                    result.Type = Data.AjaxResultType.Success;
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                _usersContract.UnitOfWork.DbContext.RollbackTran();
                result.Content = ex.Message;
            }
            return Json(result);
        }
        [Description("客户添加")]
        [HttpGet]
        public IActionResult GuestInsert()
        {
            return View();
        }
        [Description("客户添加")]
        [HttpPost]
        public IActionResult GuestInsert(UserAll user)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            user.ProportionID = 0;
            user.Token = "";
            user.CreatedTime = DateTime.Now;
            user.IsDeleted = false;
            try
            {
                _usersContract.UnitOfWork.BeginTran();
                var dd = _usersContract.InsertReturnEntity(user);
                UserLogin userLogin = new UserLogin();
                userLogin.UserID = dd.Id;
                userLogin.LoginName = user.Phone;
                userLogin.Password = "123456";
                userLogin.LoginType = 0;
                userLogin.IsDeleted = false;
                _userLoginContract.Insert(userLogin);

                UserRoleMap userRoleMap = new UserRoleMap();
                userRoleMap.UserId = user.Id;
                userRoleMap.RoleId = user.RoleID;
                _userRoleMapContract.Insert(userRoleMap);

                UserMap userMap = new UserMap();
                userMap.UserId = dd.Id;
                userMap.AgentId = user.AgentID;
                userMap.AgentSalesmanId = user.AgentSalesmanID;
                userMap.InterfaceId = user.InterfaceID;
                userMap.InterfaceSalesmanId = user.InterfaceSalesmanID;
                userMap.SuperId = 1;
                userMap.SuperSalesmanId = user.SuperSalesmanID;
                _userMapContract.Insert(userMap);
                result.Content = "操作成功";
                result.Type = Data.AjaxResultType.Success;
                _usersContract.UnitOfWork.Commit();

            }
            catch (Exception ex)
            {
                result.Content = ex.Message;
                _usersContract.UnitOfWork.Rollback();
            }
            return Json(result);
        }
        [Description("客户修改")]
        [HttpGet]
        public IActionResult GuestEdit(int id)
        {
            var goods = _usersContract.Entities.AsQueryable().Where(m => m.Id == id).First();
            ViewBag.password = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Password;
            ViewBag.loginid = _userLoginContract.Entities.AsQueryable().Where(m => m.UserID == goods.Id).First().Id;
            ViewBag.interfaceId = _userMapContract.Entities.AsQueryable().Where(m => m.UserId == goods.Id).First().InterfaceId;
            return View(goods);
        }
        [Description("客户修改")]
        [HttpPost]
        public IActionResult GuestEdit(UserDto UserDto)
        {
            AjaxResult result = new AjaxResult { Type = Data.AjaxResultType.Error, Content = "未知异常", Data = null };
            try
            {
                //开启事务
                _usersContract.UnitOfWork.DbContext.BeginTran();
                var n = _userLoginContract.Update(new UserLogin { Id = UserDto.LoginId, UserID = UserDto.UserId, LoginName = UserDto.Phone, Password = UserDto.Phone, LoginType = 1, IsDeleted = false });
                var i = _usersContract.Update(new Users
                {
                    Id = UserDto.UserId,
                    UserName = UserDto.UserName,
                    ProportionID = UserDto.ProportionID,
                    Email = UserDto.Email,
                    Phone = UserDto.Phone,
                    IdNumber = UserDto.IdNumber,
                    Sex = UserDto.Sex,
                    RoleID = UserDto.RoleId,
                    CreatedTime = UserDto.CreatedTime,
                    Token = "",
                    IsDeleted = false,

                });
                _usersContract.UnitOfWork.DbContext.CommitTran();
                if (n == 1 && i == 1)
                {
                    result.Content = "操作成功";
                    result.Type = Data.AjaxResultType.Success;
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                _usersContract.UnitOfWork.DbContext.RollbackTran();
                result.Content = ex.Message;
            }
            return Json(result);
        }
    }
}